package initial

import (
	"encoding/binary"
	"fmt"
	beego "github.com/beego/beego/v2/adapter"
	"github.com/beego/beego/v2/adapter/toolbox"
	"net"
	"os"
	"time"
	"weiboxs.com/new_h_glasses/utils"
)

//初始化任务
func StartTask() {
	//数据分析任务
	toolbox.AddTask("run_birthday", toolbox.NewTask("run_birthday", "0 15 09 * * *", func() error {
		ch := make(chan int)
		go runAnalysis(ch)
		close(ch)
		utils.LogInfo("run_birthday")
		return nil
	}))
	toolbox.StartTask()
}

func runAnalysis(i chan int) {
	//ser := services.StatisticsService{}
	//ser.AnalysisDatas()
	<-i
}

//执行UDP数据获取
func  GetUpdData()  {
	host := beego.AppConfig.String("udp::host")
	port,_ := beego.AppConfig.Int64("udp::port")
	addr, err := net.ResolveUDPAddr("udp", fmt.Sprintf("%s:%d", host, port))
	if err != nil {
		fmt.Println("Can't resolve address: ", err)
		os.Exit(1)
	}

	conn, err := net.ListenUDP("udp", addr)
	if err != nil {
		fmt.Println("Error listening:", err)
		os.Exit(1)
	}
	defer conn.Close()
	for {
		handleClient(conn)
	}
}
func handleClient(conn *net.UDPConn) {
	data := make([]byte, 1024)
	n, remoteAddr, err := conn.ReadFromUDP(data)
	if err != nil {
		fmt.Println("failed to read UDP msg because of ", err.Error())
		return
	}
	daytime := time.Now().Unix()
	fmt.Println(n, remoteAddr)
	b := make([]byte, 4)
	binary.BigEndian.PutUint32(b, uint32(daytime))
	conn.WriteToUDP(b, remoteAddr)
	fmt.Println(string(data))
}


